#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/statvfs.h>
#include <unistd.h> // 用于getcwd函数
#endif

// 函数声明 - 过程函数，通过指针参数返回磁盘使用率
void check_disk_space(const char *path, double *use_percent);

// 检查磁盘空间的实现 - 过程函数版本
void check_disk_space(const char *path, double *use_percent)
{
    // 确保指针有效
    if (use_percent == NULL)
    {
        printf("无效的指针参数\n");
        return;
    }

    // 初始化为-1表示获取失败
    *use_percent = -1.0;

#ifdef _WIN32
    // Windows 系统实现
    ULARGE_INTEGER free_bytes_available, total_number_of_bytes, total_number_of_free_bytes;

    if (GetDiskFreeSpaceExA(path, &free_bytes_available, &total_number_of_bytes, &total_number_of_free_bytes))
    {
        double total_gb = (double)total_number_of_bytes.QuadPart / (1024 * 1024 * 1024);
        double available_gb = (double)free_bytes_available.QuadPart / (1024 * 1024 * 1024);
        double used_gb = total_gb - available_gb;
        *use_percent = (used_gb / total_gb) * 100; // 通过指针赋值

        printf("总磁盘空间: %.2f GB\n", total_gb);
        printf("可用磁盘空间: %.2f GB\n", available_gb);
        printf("已使用空间: %.2f GB\n", used_gb);
        printf("使用率: %.2f%%\n", *use_percent);
    }
    else
    {
        printf("获取磁盘信息失败，错误代码: %lu\n", GetLastError());
    }
#else
    // Linux/Unix 系统实现
    struct statvfs disk_info;

    if (statvfs(path, &disk_info) == 0)
    {
        unsigned long long total_space = disk_info.f_blocks * disk_info.f_frsize;
        unsigned long long available_space = disk_info.f_bavail * disk_info.f_frsize;
        unsigned long long used_space = total_space - available_space;

        double total_gb = (double)total_space / (1024 * 1024 * 1024);
        double available_gb = (double)available_space / (1024 * 1024 * 1024);
        double used_gb = (double)used_space / (1024 * 1024 * 1024);
        *use_percent = (double)used_space / total_space * 100; // 通过指针赋值

    }
    else
    {
        perror("获取磁盘信息失败");
    }
#endif
}
